<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { onMounted, onUnmounted, ref, nextTick, provide } from 'vue'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { getConsultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
const store = useUserStore()
const route = useRoute()
let socket: Socket
const list = ref<Message[]>([])
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const initialMsg = ref(true)
const consult = ref<ConsultOrderItem>()
provide('consult', consult)
// 祖先组件提供修改数据的方法
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)
onMounted(async () => {
  // 建立链接, 创建socket.io实例
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 建立链接成功
  socket.on('connect', () => {
    console.log('链接成功了')
    list.value = []
  })
  // 建立链接异常
  socket.on('error', (event) => {
    console.log('出错了', event)
  })
  // 断开链接
  socket.on('disconnect', () => {
    // 断开链接了
    console.log('断开链接了')
  })
  // 监听消息记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log('接收到的数据', data)
    // 转换常规消息列表
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    // 追加到消息列表里
    list.value.unshift(...arr)
    // 历史记录
    loading.value = false
    if (!data.length) {
      return showToast('没有聊天记录了')
    }
    // 如果第一次加载数据 需要滚动到最下面
    nextTick(() => {
      if (initialMsg.value) {
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false
      }
    })
  })
  // 监听订单状态变化
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
  // 监听消息发送成功或者医生发来的消息
  socket.on('receiveChatMsg', async (event) => {
    console.log(event)
    list.value.push(event)
    await nextTick()
    socket.emit('updateMsgStatus', event.id)
    window.scrollTo(0, document.body.scrollHeight)
  })
})

onUnmounted(() => {
  socket.close()
})

// 拿订单详情数据

onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
})

// 2. 父组件接受子组件传出来的文字
const sendText = (text: string) => {
  // 3. 发送信息 需要通过emit触发 'sendChatMsg' 事件 发送的数据需要 发送人  收消息人 消息类型 消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}
// 发送图片
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}
// 下拉刷新
const loading = ref(false)
const onRefresh = () => {
  // 触发下拉 主动向服务端要数据
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室"></cp-nav-bar>
    <RoomStatus
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></RoomStatus>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage :list="list"></RoomMessage>
    </van-pull-refresh>

    <RoomAction
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></RoomAction>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
